<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="新增出库"
    width="1200px"
    @close="handleClose"
  >
    <!-- 第一步：选择产品 -->
    <div v-if="currentStep === 0" class="step-content">
      <el-form
        ref="step1FormRef"
        :model="step1Form"
        :rules="step1Rules"
        class="step-form"
      >
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="*合同类型">
            <el-form-item prop="cType" style="margin-top: 11px;">
              <el-select
                v-model="step1Form.cType"
                placeholder="请选择"
                style="width: 100%;"
                @change="handleCTypeChange"
              >
                <el-option label="工程类" value="1" />
                <el-option label="直销类" value="2" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*合同名称">
            <el-form-item prop="cName" style="margin-top: 11px;">
              <el-select
                v-model="step1Form.cName"
                placeholder="请选择"
                style="width: 100%;"
                @change="handleContractNameChange"
              >
                <el-option v-for="item in contractNameOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*物料类型">
            <el-form-item prop="materialType" style="margin-top: 11px;">
              <el-tree-select
                v-model="step1Form.materialType"
                :data="filterTreeData"
                placeholder="请选择"
                :props="treeSelectProps"
                filterable
                allow-clear
                check-strictly
                style="width: 100%;"
              />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*关联需求/生产加工单">
            <el-form-item prop="relatedRequirements" style="margin-top: 11px;">
              <el-cascader
                v-model="step1Form.relatedRequirements"
                :options="requirementOptions"
                :props="cascaderProps"
                placeholder="请选择"
                style="width: 100%;"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="产品列表" :rowspan="6">
            <!-- 产品列表 -->
            <div class="product-list-section">
              <el-table :data="productList" style="width: 100%" border>
                <el-table-column prop="productNo" label="关联需求" align="left" sortable />
                <el-table-column prop="productName" label="生产加工单" align="left" sortable />
                <el-table-column prop="requirementName" label="关联需求" align="left" sortable />
                <el-table-column prop="productionOrder" label="生产加工单" align="left" sortable />
                <el-table-column label="操作" align="left" width="100">
                  <template #default="scope">
                    <el-link type="primary" @click="handleViewParams(scope.row)">查看参数</el-link>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <div>
                <pagination
                  :total="productList.length"
                />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </div>

    <!-- 第二步：填写信息 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-form
        ref="step2FormRef"
        :model="step2Form"
        :rules="step2Rules"
        class="step-form"
      >
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="客户名称">
            <el-form-item style="margin-top: 11px;">
              <el-input v-model="step2Form.customerName" placeholder="客户名称" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="出库物料">
            <el-form-item style="margin-top: 11px;">
              <el-input v-model="step2Form.outboundMaterial" placeholder="出库物料" style="width: 100%;" :disabled="true" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*收货地址">
            <el-form-item prop="shippingAddress" style="margin-top: 11px;">
              <el-input v-model="step2Form.shippingAddress" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*收货联系人">
            <el-form-item prop="contactPerson" style="margin-top: 11px;">
              <el-input v-model="step2Form.contactPerson" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*收货联系方式">
            <el-form-item prop="contactPhone" style="margin-top: 11px;">
              <el-input v-model="step2Form.contactPhone" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*物流单号">
            <el-form-item prop="logisticsNo" style="margin-top: 11px;">
              <el-input v-model="step2Form.logisticsNo" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*寄出人">
            <el-form-item prop="sender" style="margin-top: 11px;">
              <el-select
                v-model="step2Form.sender"
                placeholder="请选择"
                style="width: 100%;"
              >
                <el-option label="默认当前登录用户" value="currentUser" />
                <!-- 可以根据实际需求添加更多选项 -->
              </el-select>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <template v-if="currentStep === 1">
          <el-button @click="goToPrevStep">上一步</el-button>
          <el-button type="primary" @click="handleComplete">完成</el-button>
        </template>
        <template v-else-if="currentStep === 0">
          <el-button type="primary" @click="goToNextStep">下一步</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getContractList
} from '@/api/stock'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  materialTreeData: {
    type: Array,
    required: true
  },
  // contractNameOptions: {
  //   type: Array,
  //   default: () => []
  // },
  requirementOptions: {
    type: Array,
    default: () => []
  }
})

// 定义emits
const emit = defineEmits(['close', 'complete', 'update:visible'])

// 当前步骤
const currentStep = ref(0)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 表单引用
const step1FormRef = ref(null)
const step2FormRef = ref(null)
// 合同名称选项
const contractNameOptions = ref([])
// 第一步表单数据
const step1Form = reactive({
  cType: '',
  cName: '',
  materialType: '',
  relatedRequirements: []
})

// 第二步表单数据
const step2Form = reactive({
  customerName: '',
  outboundMaterial: '',
  shippingAddress: '',
  contactPerson: '',
  contactPhone: '',
  logisticsNo: '',
  sender: 'currentUser'
})

// 第一步表单校验规则
const step1Rules = {
  cType: [
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  cName: [
    { required: true, message: '请选择合同名称', trigger: 'change' }
  ],
  materialType: [
    { required: true, message: '请选择物料类型', trigger: 'change' }
  ],
  relatedRequirements: [
    { 
      required: true, 
      type: 'array',
      min: 1,
      message: '请选择关联需求/生产加工单', 
      trigger: 'change'
    }
  ]
}

// 第二步表单校验规则
const step2Rules = {
  shippingAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入收货联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入收货联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  logisticsNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ],
  sender: [
    { required: true, message: '请选择寄出人', trigger: 'change' }
  ]
}

// 树形选择配置
const treeSelectProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  disabled: (data) => {
    // 禁用所有非一级节点
    return data.level !== undefined && data.level > 1;
  }
}

// 过滤后的树形数据，只允许选择一级节点
const filterTreeData = computed(() => {
  if (!props.materialTreeData) return [];
  
  // 深拷贝原始数据，避免修改原始数据
  const copyData = JSON.parse(JSON.stringify(props.materialTreeData));
  
  // 递归处理数据，添加level属性
  const processTree = (data, level = 1) => {
    return data.map(item => ({
      ...item,
      level,
      children: item.children ? processTree(item.children, level + 1) : []
    }));
  };
  
  return processTree(copyData);
})
// 级联选择器配置
const cascaderProps = {
  multiple: true, // 开启多选模式
  expandTrigger: 'click', // 点击展开子菜单
  collapseTags: true, // 折叠标签
  collapseTagsTooltip: true, // 鼠标悬停折叠文字时显示具体所选值
  label: 'label',
  value: 'value',
  children: 'children'
}

// 模拟产品列表数据
const productList = ref([
  {
    productNo: 'CPBH001',
    productName: '防火门/二级分类/木质门框',
    requirementName: '需求1',
    productionOrder: 'SCJHDD001'
  },
  {
    productNo: 'CPBH002',
    productName: '防火门/二级分类/木质门框',
    requirementName: '需求1',
    productionOrder: 'SCJHDD001'
  },
  {
    productNo: 'CPBH003',
    productName: '防火门/二级分类/木质门扇',
    requirementName: '需求2',
    productionOrder: 'SCJHDD004'
  }
])

// 处理合同类型变化
const handleCTypeChange = (value) => {
  console.log('value', value);
  
  // 如果选择直销类，直接显示需求名称
  if (value === '2') {
    // 实际项目中这里可能需要根据合同类型过滤合同名称选项
    ElMessage.info('直销类合同直接显示需求名称')
  } else { 
    getContractList(Number(value)).then((res) => {
      contractNameOptions.value = res.data || []
      console.log('res.data', res.data)
    })
  }
}

// 处理合同名称变化
const handleContractNameChange = (value) => {
  // 实际项目中这里可能需要根据合同名称加载相关数据
}

// 查看参数
const handleViewParams = (row) => {
  ElMessage.info(`查看${row.productName}的参数`)
  // 实际项目中这里可能会打开参数详情弹窗
}

// 进入下一步
const goToNextStep = async () => {
  try {
    await step1FormRef.value.validate()
    currentStep.value = 1
  } catch (error) {
    ElMessage.error('请完善出库单信息')
  }
}

// 回到上一步
const goToPrevStep = () => {
  currentStep.value = 0
}

// 处理完成
const handleComplete = async () => {
  try {
    await step2FormRef.value.validate()
    
    // 合并所有步骤的表单数据
    const allFormData = {
      ...step1Form,
      ...step2Form,
      productList: productList.value
    }
    
    // console.log('所有表单数据:', allFormData)
    emit('complete', allFormData)
    
    // 重置表单
    resetForm()
    emit('update:visible', false)
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 处理关闭
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
  emit('close')
}

// 弹窗关闭前的处理
const handleBeforeClose = () => {
  // 确认是否放弃当前编辑
  return new Promise((resolve) => {
    // 实际项目中这里可能需要弹出确认框
    resolve(true)
  })
}

// 重置表单
const resetForm = () => {
  currentStep.value = 0
  
  // 重置第一步表单
  if (step1FormRef.value) {
    step1FormRef.value.resetFields()
  }
  step1Form.cType = ''
  step1Form.cName = ''
  step1Form.materialType = ''
  step1Form.relatedRequirements = []
  
  // 重置第二步表单
  if (step2FormRef.value) {
    step2FormRef.value.resetFields()
  }
  step2Form.customerName = ''
  step2Form.outboundMaterial = ''
  step2Form.shippingAddress = ''
  step2Form.contactPerson = ''
  step2Form.contactPhone = ''
  step2Form.logisticsNo = ''
  step2Form.sender = 'currentUser'
}

// 初始化
onMounted(() => {
  // 初始化时可能需要加载一些数据
  // 确保没有默认选中的值
  step1Form.materialType = ''
})
</script>

<style scoped>
.step-content {
  overflow: hidden;
}

.step-form {
  margin-bottom: 20px;
}

.product-list-section {
  margin-top: 20px;
  margin-bottom: 20px;
  position: relative;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 从createModal.vue迁移相关样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #EBEEF5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
  /* padding: 18px 10px 0 10px !important; */
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}
.el-form-item {
  margin-bottom: 11px;
}
</style>
